package main

import (
	"fmt"
	"math"
	"time"
)

func isPrime(num int) bool {
	for i := 2; i <= int(math.Sqrt(float64(num))); i++ {
		if num%i == 0 {
			return false
		}
	}
	return true
}

func add(intChan chan int) {
	for i := 2; i < 5000000; i++ {
		intChan <- i
	}
	close(intChan)
}

func resPrime(reschan, intChan chan int, isOver chan bool) {
	for i := range intChan {
		if isPrime(i) {
			reschan <- i
		}
	}
	isOver <- true
}

func main() {
	intChan := make(chan int, 5000000)
	reschan := make(chan int, 1000000)
	isOver := make(chan bool, 6)
	start := time.Now().UnixMicro()
	go add(intChan)
	//统计0-500w内的素数，6个协程并行2.8s，单个协程10.4s
	for i := 0; i < 6; i++ {
		go resPrime(reschan, intChan, isOver)
	}
	go test()
	for i := 0; i < 6; i++ {
		<-isOver
	}
	close(reschan)
	close(isOver)
	count := 0
	for range reschan {
		count++
	}
	end := time.Now().UnixMicro()
	fmt.Println(len(reschan), count, end-start)
}

//协程panic，主程序也会panic结束运行,可以用recover捕获异常，使程序可以正常运行
func test() {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println("test() panic:", err)
		}
	}()
	var s1 []int
	s1[0] = 5
}
